<template>
  <div id="dialog">
    <el-dialog :title="$t('Login.title')" :visible="loginDialog" :append-to-body="true" @close="close">
      <div class="dialog_title">
        <!-- <div class="weixin"><span @click="loginWX"></span></div> -->
        <div class="weixin"><button @click="loginWX" :disabled="qqWeixin"></button></div>
        <!-- <div class="qq"><span></span></div> -->
        <div class="qq"><button :disabled="qqWeixin"></button></div>
      </div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <!-- 账号登陆 -->
        <el-tab-pane :label="$t('Login.accountLogin')" name="account">
          <div class="login">
            <el-form :model="ruleForm" ref="account" label-width="100px" class="login-ruleForm" :rules="rules" status-icon>
              <el-form-item prop="userMobile">
                <div class="iconFather">
                  <span class="el-icon-s-custom"></span>
                  <el-input type="string" v-model="ruleForm.userMobile" :placeholder="$t('share.rules.userMobile')"  maxlength="22"></el-input>
                </div>
              </el-form-item>
              <el-form-item prop="userPassword">
                <div class="iconFather">
                  <span class="el-icon-lock"></span>
                  <el-input type="password" v-model="ruleForm.userPassword" autocomplete="off" :placeholder="$t('share.rules.userPassword')" maxlength="12"></el-input>
                </div>
              </el-form-item>
              <el-form-item>
                  <el-checkbox v-model="checked">{{$t("Login.checked")}}</el-checkbox>
              </el-form-item>
            </el-form>
          </div> 
        </el-tab-pane>
        <!-- 手机登陆 -->
        <el-tab-pane :label="$t('Login.phoneLogin')" name="phone">
          <div class="login">
            <el-form :model="phoneRuleForm" ref="phone" label-width="100px" class="login-ruleForm" :rules="phoneRules" status-icon>
                    <el-form-item prop="userPhone">
                      <div class="iconFather">
                        <span class="el-icon-mobile-phone"></span>
                        <el-input type="string" v-model="phoneRuleForm.userPhone" :placeholder="$t('share.rules.userMobile')"  maxlength="11"></el-input>
                      </div>
                    </el-form-item>
                    <el-form-item prop="phoneCode" class="verificationCode">
                      <div class="iconFather">
                        <span class="el-icon-chat-dot-square"></span>
                        <el-input type="string" v-model="phoneRuleForm.phoneCode" class="codeInput" :placeholder="$t('share.rules.verificationCode')" maxlength="8"></el-input>
                        <div class="code"><button @click.prevent="phoneCode('phone')" :disabled="codeBool">{{verificationCode}}</button></div>
                      </div>
                    </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-button type="primary" :loading="loading" @click="submitForm(`${tabsName}`)">{{$t("Login.login2")}}</el-button>
      <div class="standby"><div class="standbyPass"><a>{{$t("Login.standbyPass")}}</a></div><div class="standbyId"><a @click="register()">{{$t("Login.account")}}</a></div></div>
      <el-dialog :title="$t('share.rules.scanning')" center :append-to-body="true" :visible.sync="dialogTableVisible" @close="closeQrCode" class="dialog_f">
        <div id="qrcode" ref="qrcode" ></div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";  // 引入qrcode
let Base64 = require("js-base64").Base64;
export default {
  props: {
    loginDialog: {
      type: Boolean,
    }
  },
  data () {
    // 密码验证
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("share.rules.userPhone")));
      } else {
        callback();
      }
    };
    return {
      dialogTableVisible: false,  //是否显示二维码
      WXtimer: null,  //setInterval计时器
      WXflag: true, //是否进入计时器请求数据
      Phonetimer: null, //手机验证码计时器
      Phoneflag: true,  //手机验证码是否进入计时器
      verificationCode: this.$t("share.rules.phoneCode"), //获取验证码
      dialogBool: true,  //
      codeBool: false,  //是否禁用按钮
      qqWeixin: false,    // QQ、微信，登陆按钮是否禁用，防止频繁点击
      checked: false, // 记住密码状态
      loading: false, // 提交时加载状态
      activeName: "account",  //默认标签页是哪个
      tabsName: "account",  //切换的name标识
      ruleForm: {
        userMobile: "", //账号
        userPassword: "", //密码
      },
      phoneRuleForm: {
        userPhone: "",  //手机号码
        phoneCode: "",  //手机验证码
      },
      phoneRules: {
        userPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: this.$t("share.rules.errorPhone"),trigger: "blur"}
        ],
        phoneCode: [
          { required: true, message: this.$t("share.rules.verificationCode"), trigger: "blur" },
          { pattern: /^\d{5,8}$/, message: this.$t("share.rules.errorCode"),trigger: "blur"}
        ],
      },
      rules: {// 登录验证
        userMobile: [
          { required: true, message: this.$t("share.rules.userMobile"), trigger: "blur" },
          { pattern: /^[a-zA-Z0-9@.]{4,22}$/, message: this.$t("share.rules.errorMobile"),trigger: "blur"}
        ],
        userPassword: [
          { required: true, message: this.$t("share.rules.userPassword"), trigger: "blur" },
          {required: true, pattern: /^[a-zA-Z0-9]{6,12}$/, message: this.$t("share.rules.userPasswordLength"),trigger: "blur"},
        ],
      },
    }
  },
  methods: {
    // 获取用户信息，等级
    getLevel(id) {
      var _this = this;
      // 获取用户信息，等级
      if(_this.$Cookie.getCookie("userLevel") === undefined) {
        _this.$get(`user/info/${id}`
        ).then(res => {
          if(res.code == 200) {
            _this.$Cookie.setCookie("userLevel", res.data.level, {maxAge: 604800});     // 7天秒数
          }
        })
      }
    },
    // 生成二维码
    qrcode(data) {
      new QRCode("qrcode", {
        width: 180,  
        height: 180,
        text: data, // 二维码地址
        correctLevel: QRCode.CorrectLevel.Q,  //降低检验级别
      })
      document.getElementById("qrcode").removeAttribute("title");
      // $("#qrcode").removeAttr("title");
    },
    // 微信登陆
    loginWX() {
      var _this = this;
      let strData = JSON.stringify(new Date().getTime()) + JSON.stringify(Math.round(Math.random()*100000000));   //时间戳和随机数
      let data = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx57e5163ce8035100&redirect_uri=https%3A%2F%2Fapi.shop.uekea.com%2FweChatLogin&response_type=code&scope=snsapi_userinfo&state=${strData}#wechat_redirect`
      _this.dialogTableVisible = true;  //显示二维码
      // 调用生成二维码方法
      _this.$nextTick (function () {
        _this.qrcode(data);
      })
      if(_this.WXflag) {
        _this.WXtimer = setInterval(function() {
          // 获取微信授权后的用户信息
          _this.$get("user/weChatUserInfo").then(res => {
            if(res.openid !== undefined) {
              clearInterval(_this.WXtimer);   //清除计时器
              _this.WXtimer = null;   //清空计算器
              _this.WXflag = true;  //重新赋值
              _this.closeQrCode();  //调用关闭二维码弹框方法
              _this.close();  //调用关闭登陆对话框方法
              // 请求后台购物车的数据
              _this.$get(`cart/${res.openid}`
              ).then(res => {
                if( res.code == 200) {
                  let headerArr = res.data;
                  let storeArr = _this.$store.state.goodNum;
                  let dataArr = headerArr.concat(storeArr);
                  let list = "";
                  const storeMap = new Map();
                  list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                  _this.$store.commit("goods", list);
                }
              })
              // 获取用户信息，等级
              _this.getLevel(res.openid);
              _this.$Cookie.removeCookie("userPassword");   //删除密码
              _this.$Cookie.removeCookie("checked");      //删除记住密码状态
              _this.$Cookie.setCookie("userID", res.openid, { maxAge: 604800 });     // 7天秒数
              _this.$Cookie.setCookie("userMobile", Base64.encode(res.nickname), { maxAge: 604800 });   // 微信昵称
              _this.$Cookie.setCookie("token", Base64.encode(res.access_token), { maxAge: 604800 });    // token值
              _this.$Cookie.setCookie("strData", Base64.encode(strData), { maxAge: 604800 });         // 微信二维码随机数
              _this.$store.commit("header", {nameBool: false, userName: res.nickname, openid: res.openid});  //用户名，openid,储存到vuex
              _this.$router.push({"path":"/"});
            }
          })
        },2500);
      } 
    },
    // 账号，手机登陆
    submitForm(ruleForm) {
      var _this=this;
      let user = _this.ruleForm.userMobile;   //用户名
      let pass = Base64.encode(_this.ruleForm.userPassword);  //密码
      if(_this.tabsName == "account") {
        // 账号登录
        _this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            _this.$post("user/login",{
              username: user,
              password: pass,
              type: "username",
            }).then(res=>{
              if(res.code == 200) {
                let expires_in = res.data.token.expires_in; //储存时间
                // 判断是否记住账号密码
                if(_this.checked){
                    // cookie储存，存储时间为7天
                    _this.$Cookie.setCookie("checked", _this.checked, { maxAge: expires_in });
                }else{
                  _this.$Cookie.removeCookie("checked");
                }
                _this.$Cookie.setCookie("userID", res.data.userInfo.user_id, { maxAge: expires_in });
                _this.$Cookie.setCookie("userMobile", Base64.encode(user), { maxAge: expires_in });
                _this.$Cookie.setCookie("userPassword", pass, { maxAge: expires_in });
                _this.$Cookie.setCookie("token", Base64.encode(res.data.token.access_token), { maxAge: expires_in });
                // 请求后台购物车的数据
                _this.$get(`cart/${res.data.userInfo.user_id}`
                ).then(res => {
                  if( res.code == 200) {
                    let headerArr = res.data;
                    let storeArr = _this.$store.state.goodNum;
                    let dataArr = headerArr.concat(storeArr);
                    let list = "";
                    const storeMap = new Map();
                    list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                    _this.$store.commit("goods", list);
                  }
                })
                // 获取用户信息，等级
                  _this.getLevel(res.data.userInfo.user_id);
                
                _this.$emit("close", false);
                _this.$store.commit("header", {nameBool: false, userName: user});  //header组件，用户名
                // 消息提示
                _this.$MessageAlert(true,_this.$t("Login.loginSuccess"),"success");
                _this.$refs[ruleForm].resetFields();
              } else if(res.code == 404) {
                _this.$MessageAlert(true,_this.$t("Login.loginError1"),"error");
              } else {
                _this.$MessageAlert(true,res,"error");
              }
            })
          } else {
            return false;
          }
        });
      } else if(_this.tabsName == "phone") {
        // 手机登录
        _this.$refs[ruleForm].validate((valid) => {
          if(valid) {
              _this.$post("user/login",{
                phone: _this.phoneRuleForm.userPhone,
                captcha: _this.phoneRuleForm.phoneCode,
                type: "phone",
              }).then(res => {
                if(res.code == 200) {
                  _this.$Cookie.removeCookie("userPassword");
                  _this.$Cookie.removeCookie("checked");
                  _this.$Cookie.setCookie("userID", res.data.userInfo.user_id, { maxAge: res.data.token.expires_in });
                  _this.$Cookie.setCookie("userMobile", Base64.encode(res.data.userInfo.username), { maxAge: res.data.token.expires_in });
                  _this.$Cookie.setCookie("token", Base64.encode(res.data.token.access_token), { maxAge: res.data.token.expires_in });
                  clearInterval(_this.Phonetimer);  //清除手机验证码的计时器
                  _this.Phonetimer = null;    //清空手机验证码的计时器
                  _this.verificationCode = _this.$t("share.rules.phoneCode");   //赋值，获取验证码
                  // 请求后台购物车的数据
                  _this.$get(`cart/${res.data.userInfo.user_id}`
                  ).then(res => {
                    if( res.code == 200) {
                      let headerArr = res.data;
                      let storeArr = _this.$store.state.goodNum;
                      let dataArr = headerArr.concat(storeArr);
                      let list = "";
                      const storeMap = new Map();
                      list = dataArr.filter((dataArr) => !storeMap.has(dataArr.goods_id) && storeMap.set(dataArr.goods_id, 1));
                      _this.$store.commit("goods", list);
                    }
                  })
                  // 获取用户信息，等级
                  _this.getLevel(res.data.userInfo.user_id);
                  _this.$emit("close", false);
                  _this.$store.commit("header", {nameBool: false, userName: res.data.userInfo.username});  //用户名，储存到vuex
                  _this.$MessageAlert(true,_this.$t("Login.loginSuccess"),"success");
                  _this.$refs[ruleForm].resetFields();  //清空输入框
                }
              })
          }
        });
      }
    },
    // 跳转到注册页面
    register(){
      this.$router.push({"path":"/Register"})
    },
    // 标签页切换
    handleClick(tab) {
      var _this = this;
      if(tab.name == "account") {
        // 账号登陆
        _this.tabsName = "account";
        _this.$refs["phone"].resetFields();
      } else if(tab.name == "phone") {
        // 手机登陆
        _this.tabsName = "phone";
        if(!(_this.checked && _this.$Cookie.getCookie("userMobile") && _this.$Cookie.getCookie("userPassword"))) {
          _this.checked = false;  //是否记住密码 
          _this.$refs["account"].resetFields();
        }
      }
    },
    // 获取手机短信验证码
    phoneCode(ruleForm) {
      var _this = this;
      _this.codeBool = true;
      let time = 60;
      // let flag = true;
      // 只验证手机是否有输入，部分验证，不是全部验证
      _this.$refs[ruleForm].validateField("userPhone", valid => {
        if(!valid) {
            // 倒计时
            if(_this.Phoneflag){
              // 请求验证码
              _this.$get(`user/sendSms/${_this.phoneRuleForm.userPhone}`
              ).then(res => {
                if( res.code == 200) {
                  _this.$MessageAlert(true, _this.$t("share.rules.succSend"),"success");
                } else {
                  _this.$MessageAlert(true, _this.$t("share.rules.errSend"),"error");
                }
              }).catch( ()=> {
                _this.codeBool = false;
              });
              // 倒计时
              _this.Phonetimer = setInterval(function() {
                  _this.Phoneflag = false;
                  _this.codeBool = true;
                  if(time == 0){
                      _this.verificationCode = _this.$t("share.rules.phoneCode");
                      clearInterval(_this.Phonetimer);
                      time = 60;
                      _this.Phoneflag = true;
                      _this.codeBool = false;
                  }else {
                      _this.verificationCode = time + " s "+_this.$t("share.rules.Resend");
                      time--;
                  }
              },1000);
            }
        } else {
          _this.codeBool = false;
        }
      });
    },
    // 关闭登陆对话框
    close() {
      var _this = this;
      _this.$refs["phone"].resetFields();   //清除输入框内容
      _this.$refs["account"].resetFields();
      _this.$emit("close",false);   
      clearInterval(_this.Phonetimer);  //清除手机验证码的计时器
      _this.Phonetimer = null;    //清空手机验证码的计时器
      _this.Phoneflag = true;     //手机验证码重新赋值
    },
    // 关闭微信二维码
    closeQrCode() {
      var _this = this;
      clearInterval(this.WXtimer);   //清除微信请求服务器的计时器
      _this.qqWeixin = true;
      setTimeout(function() {
        _this.qqWeixin = false;
      }, 1000);
      _this.WXflag = true;
      _this.WXtimer = null;
      _this.dialogTableVisible = false;  //关闭弹框
      _this.$refs.qrcode.innerHTML = ""; //清空弹框内容
    },
    // 关闭微信二维码和登陆框的请求和计时器
    closeRequestTimer() {
      var _this = this;
      // 微信二维码弹框
      if(_this.$refs.qrcode != undefined) {
        clearInterval(_this.WXtimer);   //清除微信请求服务器的计时器
        _this.WXflag = true;
        _this.WXtimer = null;
        _this.$refs.qrcode.innerHTML = ""; //清空微信二维码弹框内容
      }
      // 登陆弹框的手机验证码
      if(_this.Phonetimer != null) {
        clearInterval(_this.Phonetimer);  //清除手机验证码的计时器
        _this.Phonetimer = null;    //清空手机验证码的计时器
        _this.Phoneflag = true;     //手机验证码重新赋值
      }
      _this.dialogTableVisible = false;  //关闭微信二维码弹框
      _this.$emit("close", false);  //关闭登陆弹框
      _this.$refs["phone"].resetFields();   //清除输入框内容
      _this.$refs["account"].resetFields();
    }
  },
  watch:{
    $route:{
      handler(){
        this.closeRequestTimer(); //调用关闭请求和计时器方法
      },
      // 深度观察监听
      deep: true
    }
  },
  created() {
    var _this = this;
    if(_this.$Cookie.getCookie("checked") != undefined) {
      _this.ruleForm.userMobile = Base64.decode(_this.$Cookie.getCookie("userMobile"));
      _this.ruleForm.userPassword = Base64.decode(_this.$Cookie.getCookie("userPassword"));
      _this.checked = true;
    } else {
      _this.ruleForm.userMobile = "";
      _this.ruleForm.userPassword = "";
      _this.phoneRuleForm.userPhone = "";
      _this.phoneRuleForm.phoneCode = "";
    }
  },
  beforeDestroy() {
    this.closeRequestTimer(); //调用关闭请求和计时器方法
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-dialog {
  margin-top: 21vh !important;
  width: 450px;
}
/deep/ .el-dialog__body {
  padding-top: 15px;
}
.weixin {
  display: inline-block;
  margin-right: 32px;
  button {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    // display: inline-block;
    background: url(/img/fouricon.4b045a21.png) -51px 0px no-repeat;
    background-size: 215%;
  }
  button:hover {
    background: url("./../../public/img/fouricon.png") -51px -52px no-repeat;
    background-size: 215%;
    
  }
  // span {
  //   width: 45px;
  //   height: 45px;
  //   border-radius: 50%;
  //   display: inline-block;
  //   background: url(/img/fouricon.4b045a21.png) -51px 0px no-repeat;
  //   background-size: 215%;
  //   cursor:pointer;
  // }
  // span:hover {
  //   background: url("./../../public/img/fouricon.png") -51px -52px no-repeat;
  //   background-size: 215%;
    
  // }
}
.qq {
  display: inline-block;
  button {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: inline-block;
    background: url("./../../public/img/fouricon.png") -3px 0px no-repeat;
    background-size: 215%;
    cursor:pointer;
  }
  button:hover {
    background: url("./../../public/img/fouricon.png") -3px -52px no-repeat;
    background-size: 215%;
  }
  // span {
  //   width: 45px;
  //   height: 45px;
  //   border-radius: 50%;
  //   display: inline-block;
  //   background: url("./../../public/img/fouricon.png") -3px 0px no-repeat;
  //   background-size: 215%;
  //   cursor:pointer;
  // }
  // span:hover {
  //   background: url("./../../public/img/fouricon.png") -3px -52px no-repeat;
  //   background-size: 215%;
  // }
}
.iconFather {
  position: relative;
}
.el-icon-s-custom,.el-icon-lock,.el-icon-mobile-phone,.el-icon-chat-dot-square{
  font-size: 22px;
  position: absolute;
  top: 9px;
  left: 11px;
  z-index: 1;
}
.el-button{
  display: block;
  font-size: 20px;
  margin: auto;
  letter-spacing:2px;
  margin-top: 20px;
  background-color: transparent;
  border: 1px solid black;
  border-radius: 0px;
  color: black;
}
.el-button:hover {
  background-color: black;
  border: 1px solid black;
  color: white;
}
.el-button--primary:focus {
  background-color: black;
  border: 1px solid black;
}
.standbyPass {
  margin-bottom: 5px;
}
.standbyPass,.standbyId{
  font-size: 14px;
  text-decoration:underline;
  a {
    color: #409EFF;
  }
}
/deep/ .el-tabs__header {
  margin: 0px;
}
/deep/ .el-tabs--card>.el-tabs__header {
      border-bottom: 1px solid #ccc;
}
/deep/ .el-tabs__nav {
      border-top: 1px solid #ccc !important;
      border-left: 1px solid #ccc !important;
      border-right: 1px solid #ccc !important;
}
/deep/ .el-tabs__item {
  border-left: 1px solid #ccc !important;
}
/deep/ .el-tabs__item:first-child {
  border-left: none !important;
}
/deep/ .dialog_title{
  text-align: center;
  margin-bottom: 20px;
}
.login {
  margin: auto;
  margin-top: 0px;
  border: 1px solid #ccc;
  border-top: 0px;
  padding: 0px 25px;
  display: flex;
  flex-direction: column;
  .left {
    width: 250px;
    height: 250px;
    h2 {
      color: #0f998c;
      font-size: 23px;
    }
    div {
      color: #a9b4b6;
      font-size: 14px;
    }
  }
  .login-lin {
    margin: auto;
    height: 280px;
    width: 1px;
    background:linear-gradient(#fff,#999,#999,#fff);
  }
  .login-ruleForm{
    position: relative;
  }
  .el-form-item {
    margin-top: 20px;
  }
}
/deep/ .el-form-item__content{
  margin: 0px !important;
  line-height: 25px;
}
/deep/ .el-input input{
  padding-left: 45px;
}
.verificationCode {
  .code {
    border: 1px solid #DCDFE6;
    color: #666;
    line-height: 38px;
    width: 120px;
    text-align: center;
    float: right;
    border-radius: 5px;
    button:hover {
      cursor:pointer;
    }
  }
  .codeInput {
    width: 180px;
    display: inline-block;
  }
}
#qrcode {
  display: inline-block;
  margin-left: 115px;
  margin-top: 35px;
  margin-bottom: 40px;
}
</style>